<template>
  <div class="simple-model-training">
    <div class="page-header">
      <h1>🤖 智能模型训练中心</h1>
      <p>创建和训练电商业务相关的机器学习模型</p>
    </div>

    <!-- 模型创建表单 -->
    <el-card class="form-card" v-if="!showTrainingProgress">
      <template #header>
        <div class="card-header">
          <span>🚀 创建新模型</span>
          <el-tag type="success" size="small">支持真实训练</el-tag>
        </div>
      </template>

      <el-form 
        :model="modelForm" 
        :rules="formRules" 
        ref="formRef" 
        label-width="120px"
        class="model-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模型名称" prop="name">
              <el-input 
                v-model="modelForm.name" 
                placeholder="请输入模型名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型类型" prop="model_type">
              <el-select 
                v-model="modelForm.model_type" 
                placeholder="选择模型类型"
                @change="handleTypeChange"
                style="width: 100%"
              >
                <el-option 
                  v-for="type in modelTypes" 
                  :key="type.value"
                  :label="type.label" 
                  :value="type.value"
                >
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>{{ type.label }}</span>
                    <el-tag size="small" type="info">{{ type.category }}</el-tag>
                  </div>
                  <div style="font-size: 12px; color: #999; margin-top: 2px;">
                    {{ type.description }}
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 显示选中模型类型的详细信息 -->
        <el-form-item v-if="selectedModelType" label="模型说明">
          <el-alert
            :title="selectedModelType.label"
            :description="selectedModelType.business_value"
            type="info"
            show-icon
            :closable="false"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="算法选择" prop="algorithm">
              <el-select 
                v-model="modelForm.algorithm" 
                placeholder="选择算法"
                :disabled="!modelForm.model_type"
                @change="handleAlgorithmChange"
                style="width: 100%"
              >
                <el-option 
                  v-for="algo in availableAlgorithms" 
                  :key="algo.value"
                  :label="algo.label" 
                  :value="algo.value"
                >
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>{{ algo.label }}</span>
                    <div>
                      <el-tag size="small" :type="getComplexityType(algo.complexity)">
                        {{ getComplexityLabel(algo.complexity) }}
                      </el-tag>
                      <el-tag size="small" type="success" style="margin-left: 4px;">
                        {{ algo.accuracy }}
                      </el-tag>
                    </div>
                  </div>
                  <div style="font-size: 12px; color: #999; margin-top: 2px;">
                    {{ algo.description }} · 训练时间: {{ algo.training_time }}
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据集" prop="dataset">
              <el-select 
                v-model="modelForm.dataset" 
                placeholder="选择数据集"
                :disabled="!modelForm.model_type"
                style="width: 100%"
              >
                <el-option 
                  v-for="dataset in availableDatasets" 
                  :key="dataset.value"
                  :label="dataset.label" 
                  :value="dataset.value"
                >
                  <div>{{ dataset.label }}</div>
                  <div style="font-size: 12px; color: #999; margin-top: 2px;">
                    {{ dataset.description }}
                  </div>
                  <div style="font-size: 11px; color: #666; margin-top: 2px;">
                    特征: {{ dataset.features ? dataset.features.join(', ') : '自动生成' }}
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="模型描述" prop="description">
          <el-input 
            v-model="modelForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入模型描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="startTraining" :loading="creating">
            <el-icon><VideoPlay /></el-icon>
            开始训练
          </el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 训练进度 -->
    <el-card v-if="showTrainingProgress" class="training-progress-card">
      <template #header>
        <div class="card-header">
          <span>🔄 模型训练进度</span>
          <el-tag :type="getStatusType(trainingStatus)" size="small">
            {{ getStatusText(trainingStatus) }}
          </el-tag>
        </div>
      </template>

      <div class="training-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模型名称">{{ currentModel.name }}</el-descriptions-item>
          <el-descriptions-item label="模型类型">{{ currentModel.model_type }}</el-descriptions-item>
          <el-descriptions-item label="算法">{{ currentModel.algorithm }}</el-descriptions-item>
          <el-descriptions-item label="数据集">{{ currentModel.dataset }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatTime(trainingStartTime) }}</el-descriptions-item>
          <el-descriptions-item label="训练状态">
            <el-tag :type="getStatusType(trainingStatus)">{{ getStatusText(trainingStatus) }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="progress-section">
        <h4>训练进度</h4>
        <el-progress 
          :percentage="trainingProgress" 
          :status="trainingProgress === 100 ? 'success' : 'active'"
          :stroke-width="20"
        />
        <p class="progress-text">{{ progressMessage }}</p>
      </div>

      <div class="logs-section">
        <h4>训练日志</h4>
        <div class="logs-container">
          <pre class="logs-content">{{ trainingLogs }}</pre>
        </div>
      </div>

      <div class="results-section" v-if="trainingResults">
        <h4>训练结果</h4>
        <el-row :gutter="20">
          <el-col :span="12" v-if="trainingResults.accuracy">
            <el-card class="metric-card">
              <el-statistic title="准确率" :value="(trainingResults.accuracy * 100).toFixed(2)" suffix="%" />
            </el-card>
          </el-col>
          <el-col :span="12" v-if="trainingResults.f1_score">
            <el-card class="metric-card">
              <el-statistic title="F1分数" :value="trainingResults.f1_score" :precision="4" />
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="actions-section">
        <el-button @click="backToForm">返回配置</el-button>
        <el-button type="primary" @click="viewModel" v-if="trainingStatus === 'trained'">
          查看模型
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import { 
  getModelTypes, 
  getModelAlgorithms, 
  getModelDatasets, 
  getModelDefaultConfig,
  createModel,
  startTraining as startModelTraining,
  getTrainingStatus
} from '@/api/models'

// 响应式数据
const formRef = ref(null)
const modelTypes = ref([])
const availableAlgorithms = ref([])
const availableDatasets = ref([])
const creating = ref(false)
const showTrainingProgress = ref(false)

// 表单数据
const modelForm = ref({
  name: '',
  model_type: '',
  algorithm: '',
  dataset: '',
  description: '',
  training_params: {}
})

// 训练状态
const currentModel = ref({})
const trainingStatus = ref('idle')
const trainingProgress = ref(0)
const progressMessage = ref('')
const trainingLogs = ref('')
const trainingStartTime = ref(null)
const trainingResults = ref(null)
const statusCheckInterval = ref(null)

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
    { min: 2, max: 50, message: '模型名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  model_type: [
    { required: true, message: '请选择模型类型', trigger: 'change' }
  ],
  algorithm: [
    { required: true, message: '请选择算法', trigger: 'change' }
  ],
  dataset: [
    { required: true, message: '请选择数据集', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入模型描述', trigger: 'blur' },
    { min: 10, max: 200, message: '描述长度在 10 到 200 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const selectedModelType = computed(() => {
  return modelTypes.value.find(type => type.value === modelForm.value.model_type)
})

// 从后端加载模型类型
const loadModelTypes = async () => {
  try {
    const response = await getModelTypes()
    if (response.success) {
      modelTypes.value = response.data.model_types
    } else {
      ElMessage.error('获取模型类型失败')
    }
  } catch (error) {
    console.error('加载模型类型失败:', error)
    ElMessage.error('加载模型类型失败')
  }
}

// 加载算法列表
const loadAlgorithms = async (modelType) => {
  try {
    const response = await getModelAlgorithms({ model_type: modelType })
    if (response.success) {
      availableAlgorithms.value = response.data.algorithms
    } else {
      availableAlgorithms.value = []
    }
  } catch (error) {
    console.error('加载算法列表失败:', error)
    availableAlgorithms.value = []
  }
}

// 加载数据集列表
const loadDatasets = async (modelType) => {
  try {
    const response = await getModelDatasets({ model_type: modelType })
    if (response.success) {
      availableDatasets.value = response.data.datasets
    } else {
      availableDatasets.value = []
    }
  } catch (error) {
    console.error('加载数据集列表失败:', error)
    availableDatasets.value = []
  }
}

// 方法
const handleTypeChange = async () => {
  // 清空相关选择
  modelForm.value.algorithm = ''
  modelForm.value.dataset = ''
  modelForm.value.training_params = {}

  if (modelForm.value.model_type) {
    // 并行加载算法和数据集
    await Promise.all([
      loadAlgorithms(modelForm.value.model_type),
      loadDatasets(modelForm.value.model_type)
    ])
  }
}

const handleAlgorithmChange = () => {
  // 可以在这里设置算法特定的默认参数
  modelForm.value.training_params = {}
}

const startTraining = async () => {
  try {
    await formRef.value.validate()
    creating.value = true

    // 创建模型
    const createResponse = await createModel(modelForm.value)
    if (!createResponse.success) {
      throw new Error(createResponse.message)
    }

    const modelId = createResponse.data.id
    currentModel.value = { ...modelForm.value, id: modelId }

    // 开始训练
    const trainingResponse = await startModelTraining(modelId)
    if (!trainingResponse.success) {
      throw new Error(trainingResponse.message)
    }

    // 切换到训练进度页面
    showTrainingProgress.value = true
    trainingStatus.value = 'training'
    trainingStartTime.value = new Date()
    trainingProgress.value = 0
    progressMessage.value = '正在初始化训练...'
    trainingLogs.value = '开始训练模型...\n'

    // 开始轮询训练状态
    startStatusPolling(modelId)

    ElMessage.success('模型训练已开始')

  } catch (error) {
    ElMessage.error(error.message || '开始训练失败')
  } finally {
    creating.value = false
  }
}

const startStatusPolling = (modelId) => {
  statusCheckInterval.value = setInterval(async () => {
    try {
      const response = await getTrainingStatus(modelId)
      if (response.success) {
        const status = response.data
        trainingStatus.value = status.status
        trainingProgress.value = status.progress || 0
        progressMessage.value = status.message || ''
        trainingLogs.value = status.logs || ''

        if (status.status === 'trained') {
          trainingResults.value = status.results
          clearInterval(statusCheckInterval.value)
          ElMessage.success('模型训练完成！')
        } else if (status.status === 'failed') {
          clearInterval(statusCheckInterval.value)
          ElMessage.error('模型训练失败')
        }
      }
    } catch (error) {
      console.error('获取训练状态失败:', error)
    }
  }, 2000) // 每2秒检查一次
}

const resetForm = () => {
  formRef.value.resetFields()
  modelForm.value.training_params = {}
  availableAlgorithms.value = []
  availableDatasets.value = []
}

const backToForm = () => {
  showTrainingProgress.value = false
  if (statusCheckInterval.value) {
    clearInterval(statusCheckInterval.value)
  }
}

const viewModel = () => {
  // 跳转到模型详情页面
  ElMessage.info('跳转到模型详情页面')
}

// 辅助函数
const getComplexityType = (complexity) => {
  const typeMap = {
    'low': 'success',
    'medium': 'warning',
    'high': 'danger'
  }
  return typeMap[complexity] || 'info'
}

const getComplexityLabel = (complexity) => {
  const labelMap = {
    'low': '简单',
    'medium': '中等',
    'high': '复杂'
  }
  return labelMap[complexity] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    'idle': 'info',
    'training': 'warning',
    'trained': 'success',
    'failed': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'idle': '待训练',
    'training': '训练中',
    'trained': '训练完成',
    'failed': '训练失败'
  }
  return textMap[status] || '未知'
}

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

// 生命周期
onMounted(() => {
  loadModelTypes()
})

onUnmounted(() => {
  if (statusCheckInterval.value) {
    clearInterval(statusCheckInterval.value)
  }
})
</script>

<style scoped>
.simple-model-training {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
  font-size: 16px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.model-form {
  padding: 20px 0;
}

.form-actions {
  margin-top: 30px;
  text-align: right;
}

.form-actions .el-button {
  margin-left: 10px;
}

.training-progress-card {
  margin-top: 20px;
}

.training-info {
  margin-bottom: 30px;
}

.progress-section {
  margin-bottom: 30px;
}

.progress-section h4 {
  margin-bottom: 15px;
  color: #333;
}

.progress-text {
  margin-top: 10px;
  color: #666;
  text-align: center;
}

.logs-section {
  margin-bottom: 30px;
}

.logs-section h4 {
  margin-bottom: 15px;
  color: #333;
}

.logs-container {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 15px;
  max-height: 300px;
  overflow-y: auto;
}

.logs-content {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  color: #333;
  margin: 0;
  white-space: pre-wrap;
}

.results-section {
  margin-bottom: 30px;
}

.results-section h4 {
  margin-bottom: 15px;
  color: #333;
}

.metric-card {
  text-align: center;
}

.actions-section {
  text-align: right;
}

.actions-section .el-button {
  margin-left: 10px;
}

.el-alert {
  margin-bottom: 15px;
}
</style>
